package com.ruoyi.web.cp.schuedule;

import com.ruoyi.web.cp.service.ObService;
import com.ruoyi.web.cp.service.RmService;
import com.ruoyi.web.cp.service.SendFitService;
import com.ruoyi.web.cp.service.merge.MergeRmobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Slf4j
@Configuration
public class RmobTask {
    @Autowired
    private RmService rmService;
    @Autowired
    private ObService obService;
    @Autowired
    private MergeRmobService mergeService;
    @Autowired
    private Executor biggerTaskExecutor;
    @Autowired
    private SendFitService sendFitService;

    @Scheduled(fixedDelayString = "300000")
    public void execute() {
        // 1. 更新 RM 和 OB 详情
        CompletableFuture<Void> rmFuture = runAsyncTask(() -> rmService.getRmDetail(), "Error in updating RM detail");
        CompletableFuture<Void> obFuture = runAsyncTask(() -> obService.getObDetail(), "Error in updating OB detail");
        //2. 合并 RM 和 OB
        CompletableFuture.allOf(rmFuture, obFuture)
                .thenRun(this::mergeRmOb)
                .thenRun(sendFitService::sendRmobFit)
                .exceptionally(ex -> {
                    log.error("Error in executing all tasks", ex);
                    return null;
                }).join();
    }

    /**
     * 异步执行任务并捕获异常
     *
     * @param task   要执行的任务
     * @param errMsg 错误信息
     * @return CompletableFuture
     */
    private CompletableFuture<Void> runAsyncTask(Runnable task, String errMsg) {
        return CompletableFuture.runAsync(task, biggerTaskExecutor)
                .exceptionally(ex -> {
                    log.error(errMsg, ex);
                    return null;
                });
    }


    /**
     * 合并 RM 和 OB 并处理相关逻辑
     */
    private void mergeRmOb() {
        runAsyncTask(() -> {
            log.info("开始执行-->mergeRmOb");
            // 1. 合并 RM 和 OB
            mergeService.mergeRmOb();

            // 2. 清理对冲比赛
//            boolean cleaned = mergeService.cleanRmobMerge();
//            if (cleaned) {
//                // 如果有清理，更新 RM 和 OB 详情
//                CompletableFuture<Void> rmFuture = runAsyncTask(() -> rmService.getRmDetail(), "Error in re-updating RM detail");
//                CompletableFuture<Void> obFuture = runAsyncTask(() -> obService.getObDetail(), "Error in re-updating OB detail");
//                CompletableFuture.allOf(rmFuture, obFuture).join();
//                mergeService.mergeRmOb();
//            }
        }, "Error in merging RM and OB").join();
    }
}
